/*
 * Copyright 2013 Krzysztof Smigielski
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nilcaream.dirstore.cli;

import com.nilcaream.dirstore.cli.command.Command;
import com.nilcaream.dirstore.core.common.Utils;
import org.slf4j.Logger;

import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * TODO
 * <p/>
 * Krzysztof Smigielski 3/27/13 8:29 PM
 */
public class Dispatcher {

    @Inject
    private Logger logger;

    @Inject
    private Set<Command> commands;

    public void executeCommand() {
        List<Command> command = findValidCommand();
        if (command.size() == 1) {
            try {
                command.get(0).execute();
            } catch (Exception e) {
                logger.error("error: " + e.getMessage(), e);
            }
        } else {
            logger.info("invalid arguments. Run with -h for help.");
            logger.debug("available commands: " + commands.toString());
            logger.debug("matching commands: " + command.toString());
        }
        logger.debug("cache stats: " + Utils.getCacheStats());
    }

    private List<Command> findValidCommand() {
        List<Command> matchingCommands = new ArrayList<>();
        for (Command command : commands) {
            if (command.isValid()) {
                matchingCommands.add(command);
            }
        }
        return matchingCommands;
    }
}
